<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="700px"
    :before-close="handleClose"
  >
    <div v-loading="loading" class="notification-detail-dialog">
      <el-empty
        v-if="!loading && notifications.length === 0"
        description="暂无通知详情"
      />

      <div v-else class="notification-list">
        <div
          v-for="notification in notifications"
          :key="notification.id"
          class="notification-item"
          :class="{ unread: notification.isRead === 0 }"
        >
          <!-- 发送者头像 -->
          <el-avatar
            :src="getImageUrl(notification.sender.avatar)"
            :size="40"
            class="sender-avatar"
          >
            <IconifyIconOffline icon="ep:user" />
          </el-avatar>

          <!-- 通知内容 -->
          <div class="notification-body">
            <div class="notification-header">
              <span class="sender-name">{{
                notification.sender.nickName
              }}</span>
              <span class="action-text">{{ notification.actionText }}</span>
              <el-badge
                v-if="notification.isRead === 0"
                is-dot
                class="unread-dot"
              />
            </div>

            <!-- 通知内容：优先显示commentDetail.content -->
            <div class="notification-content">
              {{ getNotificationContent(notification) }}
            </div>

            <!-- 目标信息：根据通知类型显示文章或评论信息 -->
            <div
              v-if="
                notification.target && notification.targetType === 'article'
              "
              class="target-info"
            >
              <el-tag size="small" type="info">文章</el-tag>
              <span class="target-title">{{ notification.target.title }}</span>
            </div>
            <div v-else-if="notification.commentDetail" class="target-info">
              <el-tag size="small" type="info">评论</el-tag>
              <span class="target-title">{{
                notification.commentDetail.content
              }}</span>
            </div>

            <div class="notification-footer">
              <span class="time-text">
                <IconifyIconOffline icon="ep:clock" />
                {{ formatTime(notification.createTime) }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
          v-if="hasUnread"
          type="primary"
          :loading="markReadLoading"
          @click="handleMarkAllRead"
        >
          全部标记为已读
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import type {
  NotificationDetailItem,
  GroupedDetailQuery
} from "@/types/notification-grouped";
import {
  getGroupedNotificationDetailsApi,
  markGroupedNotificationsAsReadApi
} from "@/api/notification-grouped";
import dayjs from "dayjs";

interface Props {
  modelValue: boolean;
  query?: GroupedDetailQuery;
  title?: string;
}

interface Emits {
  (e: "update:modelValue", value: boolean): void;
  (e: "markRead"): void;
}

const props = withDefaults(defineProps<Props>(), {
  query: undefined,
  title: "通知详情"
});

const emit = defineEmits<Emits>();

// 响应式数据
const loading = ref(false);
const markReadLoading = ref(false);
const notifications = ref<NotificationDetailItem[]>([]);

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: value => emit("update:modelValue", value)
});

const dialogTitle = computed(() => {
  if (props.title) return props.title;
  if (notifications.value.length > 0) {
    return `${notifications.value[0].typeName} (${notifications.value.length}条)`;
  }
  return "通知详情";
});

const hasUnread = computed(() => {
  return notifications.value.some(n => n.isRead === 0);
});

// 加载通知详情
const loadNotificationDetails = async () => {
  if (!props.query) return;

  loading.value = true;
  try {
    const response = await getGroupedNotificationDetailsApi(props.query);
    if (response.code === 200 && response.data) {
      notifications.value = response.data;
    } else {
      ElMessage.error(response.message || "加载失败");
    }
  } catch (error) {
    console.error("加载通知详情失败:", error);
    ElMessage.error("加载失败");
  } finally {
    loading.value = false;
  }
};

// 标记全部为已读
const handleMarkAllRead = async () => {
  if (!props.query) return;

  markReadLoading.value = true;
  try {
    const response = await markGroupedNotificationsAsReadApi({
      type: props.query.type,
      targetType: props.query.targetType,
      targetId: props.query.targetId
    });

    if (response.code === 200) {
      ElMessage.success("已标记为已读");
      // 更新本地状态
      notifications.value.forEach(n => {
        n.isRead = 1;
        n.readTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
      });
      emit("markRead");
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("标记已读失败:", error);
    ElMessage.error("操作失败");
  } finally {
    markReadLoading.value = false;
  }
};

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false;
};

// 处理图片URL
const getImageUrl = (url: string) => {
  if (!url) return "";
  if (url.startsWith("http")) return url;
  return `http://localhost:8081${url.startsWith("/") ? "" : "/"}${url}`;
};

// 获取通知内容：优先显示commentDetail.content
const getNotificationContent = (notification: NotificationDetailItem) => {
  // 对于评论/回复/点赞评论类型，优先显示评论内容
  if (notification.commentDetail?.content) {
    return notification.commentDetail.content;
  }
  // 其次显示actionText
  if (notification.actionText) {
    return notification.actionText;
  }
  // 兼容旧数据：返回空字符串
  return "";
};

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};

// 监听dialog打开
watch(
  () => props.modelValue,
  newVal => {
    if (newVal && props.query) {
      loadNotificationDetails();
    } else {
      notifications.value = [];
    }
  }
);
</script>

<style scoped lang="scss">
// 移动端适配
@media screen and (width <= 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
  }

  .notification-detail-dialog {
    max-height: 400px;

    .notification-list {
      .notification-item {
        gap: 10px;
        padding: 12px;

        .sender-avatar {
          width: 36px;
          height: 36px;
        }

        .notification-body {
          .notification-header {
            flex-wrap: wrap;

            .sender-name {
              font-size: 13px;
            }

            .action-text {
              font-size: 12px;
            }
          }

          .notification-content {
            font-size: 13px;
          }

          .target-info {
            .target-title {
              font-size: 12px;
            }
          }
        }
      }
    }
  }
}

.notification-detail-dialog {
  min-height: 200px;
  max-height: 500px;
  overflow-y: auto;

  .notification-list {
    .notification-item {
      display: flex;
      gap: 12px;
      padding: 16px;
      border-bottom: 1px solid #f0f0f0;
      transition: background-color 0.3s;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background-color: #f5f7fa;
      }

      &.unread {
        background-color: #f0f9ff;
      }

      .sender-avatar {
        flex-shrink: 0;
      }

      .notification-body {
        flex: 1;
        min-width: 0;

        .notification-header {
          display: flex;
          gap: 6px;
          align-items: center;
          margin-bottom: 8px;

          .sender-name {
            font-size: 14px;
            font-weight: 600;
            color: #303133;
          }

          .action-text {
            font-size: 13px;
            color: #606266;
          }

          .unread-dot {
            margin-left: auto;
          }
        }

        .notification-content {
          margin-bottom: 8px;
          font-size: 14px;
          line-height: 1.6;
          color: #606266;
        }

        .target-info {
          display: flex;
          gap: 8px;
          align-items: center;
          padding: 8px;
          margin-bottom: 8px;
          background-color: #f5f7fa;
          border-radius: 4px;

          .target-title {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 13px;
            color: #303133;
            white-space: nowrap;
          }
        }

        .notification-footer {
          display: flex;
          gap: 12px;
          align-items: center;

          .time-text {
            display: flex;
            gap: 4px;
            align-items: center;
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
